<template>
  <el-dialog
    top="30px"
    width="60%"
    append-to-body
    :close-on-click-modal="false"
    :before-close="beforeClose"
    :visible.sync="visible"
  >
    <el-form :model="model" label-position="left" :rules="rules" ref="form" label-width="120px">
      <el-form-item label="解保类型" prop="un_gua_type">
        <c-select
          class="form-control-ml"
          :options="enumLoanUnStatus"
          v-model="model.un_gua_type"
          placeholder="请选择解保类型"
        ></c-select>
      </el-form-item>
      <el-form-item label="解保时间" prop="un_gua_date">
        <el-date-picker
          class="form-control-ml"
          v-model="model.un_gua_date"
          :picker-options="pickerOptions"
          placeholder="解保时间"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="解保清单" prop="un_gua_attachment">
        <upload-oss
          ref="attachUpload"
          :file-list="fileList"
          placeholder="解保清单"
          accept=""
          :file-name="0"
          :dir="dir"
          :on-change="handleAttachValidate"
          :on-remove="handleAttachValidate"
          :on-complete="handleAttachComplete"
        ></upload-oss>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="btn-long" :loading="loading" @click="submit">
          保存
        </el-button>
        <el-button class="btn-long" :disabled="loading" @click="beforeClose">取消</el-button>
      </el-form-item>
    </el-form>
    <h5 class="section-title">解保明细表(共计：项目数：{{ formData.length }})</h5>
    <table class="table table-bordered vertical-align-middle text-center table-sm">
      <colgroup>
        <col width="5%" />
        <col width="14%" />
        <col width="10%" />
        <col width="10%" />
        <col width="10%" />
        <col width="10%" />
        <col width="10%" />
        <col width="10%" />
      </colgroup>
      <tr>
        <td class="td-label">序号</td>
        <td class="td-label">借款客户</td>
        <td class="td-label">客户类型</td>
        <td class="td-label">在保余额</td>
        <td class="td-label">解保金额</td>
        <td class="td-label">放款日期</td>
        <td class="td-label">到期日期</td>
        <td class="td-label">借据号</td>
      </tr>
      <tr v-for="(p, index) of editDatas" :key="index">
        <td>{{ index + 1 }}</td>
        <td>{{ p.customer_name }}</td>
        <td>{{ p.org_class_name }}</td>
        <td>{{ p.left_funds || p.warranty_amount }}</td>
        <td :class="+(model.un_gua_type || '') !== 3 ? '' : 'input-td'">
          <span v-if="+(model.un_gua_type || '') !== 3">
            {{ p.left_funds || p.warranty_amount }}
          </span>
          <el-input
            v-else
            class="w-100"
            placeholder="填写金额"
            v-model="p.un_gua_funds"
            v-input-number="{ max: p.left_funds, min: 0, fixed: 4 }"
          ></el-input>
        </td>
        <td>{{ p.loadDate }}</td>
        <td>{{ p.loadEndDate }}</td>
        <td>{{ p.iou_no }}</td>
      </tr>
    </table>
  </el-dialog>
</template>

<script>
import { arrayToString } from '@vimi/utils-tool'
import { mapGetters } from 'vuex'
import { enumLoanUnStatus } from '@/bank/views/limit/index'
// 解保日期只能选择当前月并在当日或之前 2022.11.23 冯甫
const pickerOptions = {
  disabledDate(time) {
    const date = new Date()
    return (
      time > new Date(`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} 23:59:59`) ||
      time < new Date(`${date.getFullYear()}-${date.getMonth() + 1}-01 00:00:00`)
    )
  },
}
export default {
  components: {},
  props: {
    visible: Boolean,
    formData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      pickerOptions,
      enumLoanUnStatus,
      loading: false,
      fileList: [],
      model: {
        un_gua_attachment: '',
      },
      rules: {
        un_gua_type: { required: true, message: '请选择解保类型', trigger: 'change' },
        un_gua_date: { required: true, message: '请选择解保时间', trigger: 'change' },
        un_gua_attachment: [{ required: true, message: '请上传附件', trigger: 'change' }],
      },
      tableName: 'datum_one_county_industry',
      editDatas: [],
    }
  },
  computed: {
    ...mapGetters(['clientId']),
    dir() {
      return `/bank/limit-history/unloan/${+new Date()}/${this.clientId}`
    },
  },
  watch: {
    formData: {
      handler: function () {
        this.model = {
          un_gua_attachment: '',
          un_gua_date: this.$utils.dateFormat(new Date(), 'yyyy-MM-dd'),
        }
        this.fileList = []
        this.editDatas = this.formData.map(item => {
          return { ...item }
        })
      },
      immediate: true,
      deep: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (!this.formData.length) {
            return
          }
          if (+(this.model.un_gua_type || '') === 3) {
            for (let p of this.editDatas) {
              if (!p.un_gua_funds) {
                return this.$message.warning(`请输入${p.customer_name}的解保金额！`)
              }
            }
          }
          this.$refs.attachUpload.submit()
        } else {
          this.$message.warning('请填写解保信息')
        }
      })
    },
    handleAttachValidate(file, fileList) {
      this.model.un_gua_attachment = fileList.length ? '1' : ''
      this.$refs.form.validateField('un_gua_attachment')
    },
    handleAttachComplete(files) {
      this.model.un_gua_attachment = arrayToString(files.map(it => it.url))
      this.loading = true
      const data = []
      this.editDatas.forEach(item => {
        data.push({
          customer_related_id: item.customer_related_id,
          un_gua_attachment: this.model.un_gua_attachment,
          un_gua_date: this.model.un_gua_date,
          un_gua_type: this.model.un_gua_type,
          un_gua_funds:
            +(this.model.un_gua_type || '') === 3
              ? item.un_gua_funds
              : item.left_funds || item.warranty_amount,
        })
      })
      this.$api
        .addBatch('credit', 'un_gua_record', data)
        .then(() => {
          this.$emit('success', true)
          this.$message.success('解保成功')
          this.beforeClose()
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '提交失败，请重试！')
        })
        .finally(() => {
          this.loading = false
        })
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
  },
}
</script>

<style lang="scss" scoped>
.vertical-align-middle td {
  vertical-align: middle;
}
.input-td {
  background-color: #ffffee;
}
</style>
